# -*- coding: utf-8 -*-

'''
Created on Mar 3, 2016

@author: fu_zkun@massclouds.com
'''

import ConfigParser
import threading
import os
from utils import fileutil
import logging
from functools import wraps

config_path = '/etc/massclouds/mcstudent.conf'
config_mutex = threading.Lock()

def config(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        config_mutex.acquire()
        try:
            if not os.path.exists(config_path):
                fileutil.create_file(config_path)
            return func(*args, **kwargs)
        except Exception as e:
            logging.exception(e)
            raise Exception(e)
        finally:
            config_mutex.release()
    return wrapper


def set_config_path(path):
    global config_path
    config_path = path


@config
def get_value(section, option):
    value = ''
    parser = ConfigParser.ConfigParser()
    parser.read(config_path)
    if parser.has_section(section):
        if parser.has_option(section, option):
            value = parser.get(section, option)
    return value


@config
def get_options(section):
    parser = ConfigParser.ConfigParser()
    parser.read(config_path)
    return parser.options(section)


@config
def set_value(section, option, value):
    parser = ConfigParser.ConfigParser()
    parser.read(config_path)
    if not parser.has_section(section):
        parser.add_section(section)
    parser.set(section, option, value)
    parser.write(open(config_path, 'w'))


@config
def remove_section(section):
    parser = ConfigParser.ConfigParser()
    parser.read(config_path)
    if not parser.has_section(section):
        parser.remove_section(section)
    parser.write(open(config_path, 'w'))


@config
def remove_option(section, option):
    parser = ConfigParser.ConfigParser()
    parser.read(config_path)
    if not parser.has_option(option):
        parser.remove_option(option)
    parser.write(open(config_path, 'w'))


